<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      :show-qk="showQk"
      @handleQuery="getDataList"
    >
      <template v-if="meta.indexOf('StatisticsBalanceExport') > -1" #btns>
        <el-button :loading="exportLoading" type="primary" @click="exportExcel">{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      border
      fit
      show-summary
      :summary-method="getSummaries"
      :header-row-class-name="'table-header'"
      class="doumee-element-table table_tj"
    >
      <el-table-column
        v-for="(item, index) in headList"
        :key="index"
        :prop="item.code"
        :label="item.name"
        show-overflow-tooltip
        :min-width="item.length?item.length: ''"
        align="center"
      >
        <el-table-column
          v-for="(em, dex) in item.nameVo"
          :key="dex"
          :prop="em.code"
          :label="em.name"
          :min-width="em.length?em.length: ''"
          show-overflow-tooltip
          align="center"
        />
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core'
// 引入柱状图图表，图表后缀都为 Chart
import { PieChart, BarChart } from 'echarts/charts'
// 引入提示框，标题，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent
} from 'echarts/components'
// 标签自动布局，全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features'
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers'
import QueryForm from '@/components/QueryForm'
import { queryFormConfig } from './config'
// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  PieChart,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  LegendComponent
])
import { financeCount, settlement, businessSettlement, businessSettlementHead, StatisticsBalanceExport } from '@/api'
import { parseTime } from '@/utils'
export default {
  name: 'FinanceSettlement',
  components: {
    QueryForm
  },
  data() {
    return {
      queryFormConfig,
      showQk: false,
      meta: [],
      vLog: sessionStorage.getItem('logo'),
      vName: sessionStorage.getItem('name'),
      date: parseTime(new Date()),
      dayMoney: 1000,
      mark: null,
      benchInfo: {},
      settleList: [],
      incomeMethod: [],
      paymentMethod: [],
      listLoading: true,
      exportLoading: false,
      list: [],
      headList: [],
      pagination: {
        page: 1,
        rows: 10,
        firstQueryTime: new Date()
      },
      filters: { },
      total: 0
      // （66合计 01开卡充值02场地售卖03门票售卖04套餐收入06商品收入07课程报名08活动报名72通用消费）")
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.setDate()
    this.getDataList()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    setDate() {
      // 今天00:00:00时间戳
      var start = this.dataFormat(
        new Date(new Date(new Date().toLocaleDateString()).getTime())
      )
      var curTime = this.dataFormat(new Date().getTime())
      this.$set(this.filters, 'time', [start, curTime])
      // this.filters.time = [start, curTime]
    }, // 格式化时间
    dataFormat(date) {
      // date是传入的时间
      const d = new Date(date)

      const month =
        d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
      const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
      const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
      const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
      const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()

      const times =
        d.getFullYear() +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hours +
        ':' +
        min +
        ':' +
        sec

      return times
    },
    async getDataList() {
      const headResult = await businessSettlementHead({ param: { headType: 'statistics' }})
      this.headList = headResult.recordList || []
      const { filters } = this
      businessSettlement({
        param: {
          startTime: filters.time ? filters.time[0] : '',
          endTime: filters.time ? filters.time[1] : '',
          venueId: sessionStorage.getItem('venueId'),
          headVos: this.headList
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.record.projectData
          this.incomeMethod = []
          Object.keys(res.record.orderTypeStatisticsDataVo).forEach((key) => {
            const value = parseFloat(res.record.orderTypeStatisticsDataVo[key])
            this.incomeMethod.push({ value: value, name: key + '：' + value })
          })
          this.paymentMethod = []
          Object.keys(res.record.payMethodStatistVo).forEach((key) => {
            const value = parseFloat(res.record.payMethodStatistVo[key])
            this.paymentMethod.push({ value: value, name: key + '：' + value })
          })
          // this.settleList = []
          // let lastItem
          // for (const item of res.record.list) {
          //   if (item.status === '66') {
          //     lastItem = item
          //     this.dayMoney = item.allMoney
          //     console.log(this.dayMoney)
          //   } else {
          //     this.settleList.push(item)
          //   }
          // }
          // this.settleList.push(lastItem)
          this.dayMoney = res.record.countMoneyOne
          // this.renderIncome()
          // this.renderPaymentTerm()
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('message.heji')
          return
        } else if (index === 1) {
          sums[index] = '-'
          return
        } else {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2)
          } else if (column.property.includes('.')) {
            let nums = 0
            data.forEach(s => {
              if (s.dataMap && s.dataMap[column.property.substring(column.property.lastIndexOf('\.') + 1, column.property.length)]) {
                if (!isNaN(s.dataMap[column.property.substring(column.property.lastIndexOf('\.') + 1, column.property.length)])) {
                  nums = nums + s.dataMap[column.property.substring(column.property.lastIndexOf('\.') + 1, column.property.length)]
                }
              }
            })
            sums[index] = nums.toFixed(2)
          } else {
            sums[index] = '-'
          }
        }
      })

      return sums
    },
    settleAction() {
      settlement({
        param: { settlementDate: this.date, venueId: sessionStorage.getItem('venueId'), settlementInfo: this.mark }
      }).then(res => {

      })
    },
    initData() {
      console.log(this.date)
      financeCount({ param: { settlementDate: this.date, venueId: sessionStorage.getItem('venueId') }}).then(res => {
        // console.log(res)
        this.listLoading = false
        this.incomeMethod = []
        Object.keys(res.record.incomeMethod).forEach((key) => {
          const value = parseFloat(res.record.incomeMethod[key])
          this.incomeMethod.push({ value: value, name: key + '：' + value })
        })
        console.log('this.incomeMethod', this.incomeMethod)
        this.paymentMethod = []
        Object.keys(res.record.paymentMethod).forEach((key) => {
          const value = parseFloat(res.record.paymentMethod[key])
          this.paymentMethod.push({ value: value, name: key + '：' + value })
        })
        console.log('this.paymentMethod', this.paymentMethod)
        this.settleList = []
        let lastItem
        for (var item = 1; item <= res.record.list.length; item++) {
          if (item.status === '66') {
            lastItem = item
            this.dayMoney = item.allMoney
            console.log(this.dayMoney)
          } else {
            this.settleList.push(item)
          }
        }
        this.settleList.push(lastItem)
        // this.renderIncome()
        // this.renderPaymentTerm()
      })
    },
    renderIncome() {
      const that = this
      // console.log('renderIncome', that.dayMoney)
      const chartAreaBooking = echarts.init(this.$refs.incomeWays)
      chartAreaBooking.setOption({
        title: {
          text: that.dayMoney,
          left: '125',
          top: '140',
          textStyle: {
            color: '#ff00ff',
            fontWeight: 'bolder',
            fontSize: 30,
            width: 250,
            overflow: 'truncate',
            ellipsis: '...'
          },
          textAlign: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: 'center',
          right: '0',
          orient: 'vertical'
        },
        series: [
          {
            type: 'pie',
            radius: ['60%', '80%'],
            center: ['130', '155'],
            avoidLabelOverlap: false,
            label: { show: false },
            labelLine: { show: false },
            data: that.incomeMethod
          }
        ]
      })
    },
    exportExcel() {
      const { filters } = this
      this.exportLoading = true
      StatisticsBalanceExport({
        param: {
          startTime: filters.time ? filters.time[0] : '',
          endTime: filters.time ? filters.time[1] : '',
          venueId: sessionStorage.getItem('venueId'),
          headVos: this.headList
        }
      })
        .then((res) => {
          this.exportLoading = false
          if (res.errorCode === '000000') {
            window.open(res.record.showUrl, '_blank')
          }
        })
        .catch(() => { this.exportLoading = false })
    },
    renderPaymentTerm() {
      const that = this
      // console.log('renderPaymentTerm', that.dayMoney)
      const chartAreaBooking = echarts.init(this.$refs.paymentTerm)
      chartAreaBooking.setOption({
        title: {
          text: that.dayMoney,
          left: '125',
          top: '140',
          textStyle: {
            color: '#ff00ff',
            fontWeight: 'bolder',
            fontSize: 30,
            width: 150,
            overflow: 'truncate',
            ellipsis: '...'
          },
          textAlign: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: 'center',
          right: '0',
          orient: 'vertical'
        },
        series: [
          {
            type: 'pie',
            radius: ['60%', '80%'],
            center: ['130', '150'],
            avoidLabelOverlap: false,
            label: { show: false },
            labelLine: { show: false },
            // data: [
            //   { value: Number(this.benchInfo.fixedDuration), name: this.$t('message.yjcg') + '：' + Number(this.benchInfo.fixedDuration) + this.$t('message.xiaoshi') },
            //   { value: Number(this.benchInfo.pcDuration), name: this.$t('message.qtyd') + '：' + Number(this.benchInfo.pcDuration) + this.$t('message.xiaoshi') },
            //   { value: Number(this.benchInfo.appDuration), name: this.$t('message.wlyd') + '：' + Number(this.benchInfo.appDuration) + this.$t('message.xiaoshi') }
            // ]
            data: that.paymentMethod
          }
        ]
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-header{
  display: flex;
  align-items: center;
  justify-content: left;
  margin-bottom: 30px;
  .statistics-items {
    // background-color: #f7f7f7;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 300px;
    border: solid 1px #55a3e2;
    width: calc((100% - 20px) / 2);
    margin-right: 10px;
    .chart-area-booking {
      flex: 1;
      height: 300px;
      width: 100%;
      margin: -25px 0;
      display: flex;
      align-items: center;
    }
    .statistics-title {
      padding-left: 10px;
      background-color: #55a3e2;
      color: white;
      line-height: 30px;
      font-weight: 600;
      height: 30px;
      width: 100%;
    }
  }
  .button-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-top: 10px;
    button {
      color: #fff;
      border: none;
      border-radius: 4px;
      padding: 3px 8px;
      font-size: 12px;
    }
    .settle-btn {
      background: #55a3e2;
    }
    .print-btn {
      margin-left: 15px;
      background-color: rgb(232, 158, 66);
    }
  }
}
.message-form {
  width: 100%;
  margin-top: 15px;
  .name-style {
    display: flex;
    align-items: center;
    .messag-title {
      display: inline-block;
      width: 100px;
      text-align: right;
      margin-right: 10px;
      font-size: 14px;
      font-weight: 600;
      color: #666;
    }
    .input {
      width: calc(100% - 130px);
      .money-tip {
        margin-top: 5px;
        color: #e03529;
        font-size: 12px;
        border-width: 600;
      }
    }
    .image-placehold {
      max-width: 60px;
      height: 30px;
      overflow: hidden;
      background-size: cover;
      background-position: center;
      margin-right: 5px;
    }
    span {
      font-size: 14px;
    }
  }
}
.summary-sheet {
  font-weight: 700;
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 18px;
  color: #333;
}
</style>
